package com.strong.config.security.userdetails;

import cn.hutool.core.util.StrUtil;
import com.strong.utils.security.SecurityUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.strong.utils.security.AuthorityConstants.STR_AUTHORITY_GENERAL;
import static com.strong.utils.security.AuthorityConstants.STR_AUTHORITY_SUPER;

/**
 * 用户验证服务
 *
 * @author simen
 * @date 2022/01/29
 */
@Slf4j
@Service
@Component("JwtUserDetailsService")
public class JwtUserDetailsService implements UserDetailsService {

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        // 用户名非空时，强制注册simen和admin用户
        if (StrUtil.isNotBlank(username)) {
            // 用户权限队列
            List<GrantedAuthority> listGrantedAuthority = new ArrayList<>();
            Map<String, Object> mapProperties = new HashMap<>(8);
            if (StrUtil.equals(username, "simen")) {
                listGrantedAuthority.add(new SimpleGrantedAuthority(STR_AUTHORITY_GENERAL));
                mapProperties.put("扩展属性", String.format("%s %s", username, STR_AUTHORITY_GENERAL));
                log.info("读取到已有用户[{}]，默认密码123456，[{}]", username, mapProperties);
                return new JwtUserDetails(username, SecurityUtils.signByUUID("123456"), false, listGrantedAuthority, mapProperties);
            } else if (StrUtil.equals(username, "admin")) {
                listGrantedAuthority.add(new SimpleGrantedAuthority(STR_AUTHORITY_SUPER));
                listGrantedAuthority.add(new SimpleGrantedAuthority(STR_AUTHORITY_GENERAL));
                mapProperties.put("扩展属性", String.format("%s %s、%s", username, STR_AUTHORITY_SUPER, STR_AUTHORITY_GENERAL));
                log.info("读取到已有用户[{}]，默认密码123456，[{}]", username, mapProperties);
                return new JwtUserDetails(username, SecurityUtils.signByUUID("123456"), false, listGrantedAuthority, mapProperties);
            } else {
                log.info("用户[{}]不存在", username);
                return new JwtUserDetails();
            }
        } else {
            log.info("用户为空");
            return new JwtUserDetails();
        }
    }

}
